// 歌曲数据 - 包含3首歌曲
const songs = [
    {
        title: "少一点天分",
        artist: "张碧晨 / 摩登兄弟刘宇宁",
        cover: "images/cover1.jpg",
        file: "music/song1.mp3",
        lyrics: [
            { time: 0, text: "《少一点天分》" },
            { time: 5, text: "演唱：张碧晨 / 摩登兄弟刘宇宁" },
            { time: 10, text: "词：张简君伟 / 孙盛希" },
            { time: 15, text: "曲：张简君伟 / 孙盛希" },
            { time: 20, text: "" },
            { time: 25, text: "小伤痕痛几天就愈合" },
            { time: 30, text: "依旧还能活着" },
            { time: 35, text: "小挫折哭几回就忘了就过了" },
            { time: 42, text: "天空黑了我还醒着" },
            { time: 47, text: "孤单总是会在这不离不弃陪伴着" },
            { time: 54, text: "（孤单总是陪伴着）" },
            { time: 58, text: "最忠诚的不是爱而是沉默的孤单" },
            { time: 65, text: "" },
            { time: 70, text: "我们都在爱情里少一点天分" },
            { time: 75, text: "所以才跌跌撞撞满身伤痕" },
            { time: 80, text: "总是要耗尽眼泪痛心的上了一课" },
            { time: 87, text: "才知道什么要割舍" },
            { time: 92, text: "我们折腾了多少上天的缘份" },
            { time: 97, text: "才发现世界有太多舍不得" },
            { time: 102, text: "错过了一个对的人谁晓得" },
            { time: 107, text: "" },
            { time: 112, text: "小伤痕痛几天就愈合" },
            { time: 117, text: "依旧还能活着（依旧还能活着）" },
            { time: 122, text: "小挫折哭几回就忘了就过了" },
            { time: 129, text: "天空黑了我还醒着" },
            { time: 134, text: "孤单总是会在这不离不弃陪伴着" },
            { time: 141, text: "最忠诚的不是爱而是沉默的孤单" },
            { time: 148, text: "" },
            { time: 153, text: "我们都在爱情里少一点天分" },
            { time: 158, text: "所以才跌跌撞撞满身伤痕" },
            { time: 163, text: "总是要耗尽眼泪痛心的上了一课" },
            { time: 170, text: "才知道什么要割舍" },
            { time: 175, text: "我们折腾了多少上天的缘份" },
            { time: 180, text: "（折腾了多少缘份）" },
            { time: 185, text: "才发现世界有太多舍不得" },
            { time: 190, text: "错过了一个对的人谁晓得" },
            { time: 195, text: "" },
            { time: 200, text: "紧咬着忍着痛再往前走" },
            { time: 205, text: "是否只有我（是否只有我）" },
            { time: 210, text: "终究学不懂" },
            { time: 215, text: "爱情变陌生错过再错" },
            { time: 220, text: "是否" },
            { time: 225, text: "" },
            { time: 230, text: "我们都在爱情里少一点天分" },
            { time: 235, text: "所以才跌跌撞撞满身伤痕" },
            { time: 240, text: "总是要耗尽眼泪痛心的上了一课" },
            { time: 247, text: "才知道什么要割舍" },
            { time: 252, text: "我们折腾了多少上天的缘份" },
            { time: 257, text: "（上天的缘份）" },
            { time: 262, text: "才发现世界有太多舍不得" },
            { time: 267, text: "错过了一个对的人谁晓得" },
            { time: 272, text: "" },
            { time: 277, text: "我们都在爱情里少一点天分" },
            { time: 282, text: "才发现世界有太多舍不得" },
            { time: 287, text: "爱上了一个错的人谁醒着" }
            // 完整歌词...
        ]
    },
    {
        title: "至少还有你",
        artist: "林忆莲",
        cover: "images/cover2.jpg",
        file: "music/song2.mp3",
        lyrics: [

        
    {"time": 0, "text": "《至少还有你》"},
    {"time": 5, "text": "演唱：林忆莲"},
    {"time": 10, "text": "词：林夕"},
    {"time": 15, "text": "曲：Davy Chan"},
    {"time": 20, "text": ""},
    {"time": 25, "text": "我怕来不及"},
    {"time": 30, "text": "我要抱着你"},
    {"time": 35, "text": "直到感觉你的皱纹"},
    {"time": 40, "text": "有了岁月的痕迹"},
    {"time": 45, "text": "直到肯定你是真的"},
    {"time": 50, "text": "直到失去力气"},
    {"time": 55, "text": "为了你我愿意"},
    {"time": 60, "text": "动也不能动"},
    {"time": 65, "text": "也要看着你"},
    {"time": 70, "text": "直到感觉你的发线"},
    {"time": 75, "text": "有了白雪的痕迹"},
    {"time": 80, "text": "直到视线变得模糊"},
    {"time": 85, "text": "直到不能呼吸"},
    {"time": 90, "text": "让我们形影不离"},
    {"time": 95, "text": ""},
    {"time": 100, "text": "如果全世界我也可以放弃"},
    {"time": 105, "text": "至少还有你值得我去珍惜"},
    {"time": 110, "text": "而你在这里"},
    {"time": 115, "text": "就是生命的奇迹"},
    {"time": 120, "text": "也许全世界我也可以忘记"},
    {"time": 125, "text": "只是不愿意失去你的消息"},
    {"time": 130, "text": "你掌心的痣"},
    {"time": 135, "text": "我总记得在哪里"},
    {"time": 140, "text": ""},
    {"time": 145, "text": "我怕来不及"},
    {"time": 150, "text": "我要抱着你"},
    {"time": 155, "text": "直到感觉你的发线"},
    {"time": 160, "text": "有了白雪的痕迹"},
    {"time": 165, "text": "直到视线变得模糊"},
    {"time": 170, "text": "直到不能呼吸"},
    {"time": 175, "text": "让我们形影不离"},
    {"time": 180, "text": ""},
    {"time": 185, "text": "如果全世界我也可以放弃"},
    {"time": 190, "text": "至少还有你值得我去珍惜"},
    {"time": 195, "text": "而你在这里"},
    {"time": 200, "text": "就是生命的奇迹"},
    {"time": 205, "text": "也许全世界我也可以忘记"},
    {"time": 210, "text": "只是不愿意失去你的消息"},
    {"time": 215, "text": "你掌心的痣"},
    {"time": 220, "text": "我总记得在哪里"},
    {"time": 225, "text": ""},
    {"time": 230, "text": "我们好不容易"},
    {"time": 235, "text": "我们身不由己"},
    {"time": 240, "text": "我怕时间太快"},
    {"time": 245, "text": "不够将你看仔细"},
    {"time": 250, "text": "我怕时间太慢"},
    {"time": 255, "text": "日夜担心失去你"},
    {"time": 260, "text": "恨不得一夜之间白头"},
    {"time": 265, "text": "永不分离"},
    {"time": 270, "text": ""},
    {"time": 275, "text": "如果全世界我也可以放弃"},
    {"time": 280, "text": "至少还有你值得我去珍惜"},
    {"time": 285, "text": "而你在这里"},
    {"time": 290, "text": "就是生命的奇迹"},
    {"time": 295, "text": "也许全世界我也可以忘记"},
    {"time": 300, "text": "只是不愿意失去你的消息"},
    {"time": 305, "text": "你掌心的痣"},
    {"time": 310, "text": "我总记得在哪里"},
    {"time": 315, "text": "在哪里"}
        ]
    },
    {
        title: "Mr.Mr",
        artist: "少女时代",
        cover: "images/cover3.jpg",
        file: "music/song3.mp3",
        lyrics: [
        
    {"time": 0, "text": "《Mr.Mr.》"},
    {"time": 5, "text": "가수: 소녀시대"},
    {"time": 10, "text": ""},
    {"time": 15, "text": "Let’s go!"},
    {"time": 20, "text": "사랑은 두려워"},
    {"time": 25, "text": "상대의 마음을 몰라서"},
    {"time": 30, "text": "왜 흔들어봐도"},
    {"time": 35, "text": "Oh oh oh oh oh oh oh oh"},
    {"time": 40, "text": "멀리서 봐도"},
    {"time": 45, "text": "戸惑いも不安も 消える背中"},
    {"time": 50, "text": "너를 딱 follow"},
    {"time": 55, "text": "You bad bad bad boy, you so bad"},
    {"time": 60, "text": "마지막 恋愛이면 뭐해도"},
    {"time": 65, "text": "(Mr. Mr.) 더"},
    {"time": 70, "text": "(Mr. Mr.) 말로는 堂々と"},
    {"time": 75, "text": "처음的爱면 됐어"},
    {"time": 80, "text": "(Mr. Mr.) 봐도"},
    {"time": 85, "text": "(Mr. Mr.) 빛나는 넌"},
    {"time": 90, "text": "너의 세상"},
    {"time": 95, "text": "이 별은 Mr. Mr. Mr. Mr."},
    {"time": 100, "text": "너라면 알아줄 거야"},
    {"time": 105, "text": "그 의미는 Mr. Mr."},
    {"time": 110, "text": "Mr. Mr. Mr. Mr. Mr. Mr. Mr. Mr."},
    {"time": 115, "text": "Why not? 찾던 爱"},
    {"time": 120, "text": "여기 있었어"},
    {"time": 125, "text": "지금 믿을게"},
    {"time": 130, "text": "Oh oh oh oh oh oh oh oh"},
    {"time": 135, "text": "미래의 门을 열어줄 key"},
    {"time": 140, "text": "꽉 쥔 두 손, 엇갈린 finger"},
    {"time": 145, "text": "기호를 그려"},
    {"time": 150, "text": "My mi-mi-mister, rock this world"},
    {"time": 155, "text": "마지막 恋愛이면 뭐해도"},
    {"time": 160, "text": "(Mr. Mr.) 더"},
    {"time": 165, "text": "(Mr. Mr.) 태도로 堂々と"},
    {"time": 170, "text": "처음的爱면 됐어"},
    {"time": 175, "text": "(Mr. Mr.) 봐도"},
    {"time": 180, "text": "(Mr. Mr.) 비밀의 sign"},
    {"time": 185, "text": "너의 세상"},
    {"time": 190, "text": "이 별은 Mr. Mr. Mr. Mr."},
    {"time": 195, "text": "너라면 알아줄 거야"},
    {"time": 200, "text": "그 의미는 Mr. Mr. Mr. Mr."},
    {"time": 205, "text": "1, 2, 3, 4"},
    {"time": 210, "text": "Hey, hey, hey, hey"},
    {"time": 215, "text": "Mr. Mr. Mr. Mr."},
    {"time": 220, "text": "Hey, hey, hey"},
    {"time": 225, "text": "(Hey, 이제以上) 너"},
    {"time": 230, "text": "(恋愛은) 진짜"},
    {"time": 235, "text": "(이제는) 너를"},
    {"time": 240, "text": "(Mr. Mr.) Mister"},
    {"time": 245, "text": "(저항은) 멈춰"},
    {"time": 250, "text": "(运命의)光圈 속"},
    {"time": 255, "text": "(Hey, 걸어가 两人의) Mister oh"},
    {"time": 260, "text": "마지막 恋愛이면 뭐해도"},
    {"time": 265, "text": "(Mr. Mr.) 더"},
    {"time": 270, "text": "(Mr. Mr.) 말로는 堂々と"},
    {"time": 275, "text": "처음的爱면 됐어 (Oh, you are)"},
    {"time": 280, "text": "(Mr. Mr.) 봐도 (Mr. Mr.)"},
    {"time": 285, "text": "(Mr. Mr.) 빛나는 넌 (Ooh oh)"},
    {"time": 290, "text": "너의 세상"},
    {"time": 295, "text": "이 별은 Mr. Mr. Mr. Mr."},
    {"time": 300, "text": "너라면 알아줄 거야"},
    {"time": 305, "text": "그 의미는 Mr. Mr. Mr. Mr."}
]
    }
];

// 播放器初始化
const audioPlayer = document.getElementById('audio-player');
const playBtn = document.getElementById('play-btn');
const prevBtn = document.getElementById('prev-btn');
const nextBtn = document.getElementById('next-btn');
const progress = document.getElementById('progress');
const currentTimeEl = document.getElementById('current-time');
const durationEl = document.getElementById('duration');
const volumeControl = document.getElementById('volume');
const playlistEl = document.getElementById('playlist');
const lyricsEl = document.getElementById('lyrics');
const searchEl = document.getElementById('search');
const coverEl = document.getElementById('cover');
const songTitleEl = document.getElementById('song-title');
const artistEl = document.getElementById('artist');

let currentSongIndex = 0;
let isPlaying = false;
let isDraggingProgress = false;

// 加载歌曲
function loadSong(index) {
    const song = songs[index];
    audioPlayer.src = song.file;
    coverEl.src = song.cover;
    songTitleEl.textContent = song.title;
    artistEl.textContent = song.artist;
    
    updatePlaylistHighlight(index);
    displayLyrics(song.lyrics);
    
    if (isPlaying) {
        audioPlayer.play().catch(e => console.log("自动播放被阻止:", e));
    }
}

// 显示歌词
function displayLyrics(lyrics) {
    lyricsEl.innerHTML = '';
    lyrics.forEach(line => {
        const p = document.createElement('p');
        p.textContent = line.text;
        p.setAttribute('data-time', line.time);
        lyricsEl.appendChild(p);
    });
}

// 更新当前播放的歌词
function updateLyrics() {
    if (isDraggingProgress) return;
    
    const currentTime = audioPlayer.currentTime;
    const lines = lyricsEl.querySelectorAll('p');
    
    let currentLine = null;
    
    lines.forEach(line => {
        line.classList.remove('current');
        const lineTime = parseFloat(line.getAttribute('data-time'));
        
        if (lineTime <= currentTime) {
            currentLine = line;
        }
    });
    
    if (currentLine) {
        currentLine.classList.add('current');
        currentLine.scrollIntoView({
            behavior: 'smooth',
            block: 'center'
        });
    }
}

// 更新播放列表高亮
function updatePlaylistHighlight(index) {
    const items = playlistEl.querySelectorAll('li');
    items.forEach((item, i) => {
        item.classList.toggle('playing', i === index);
    });
}

// 播放歌曲
function playSong() {
    isPlaying = true;
    playBtn.textContent = '暂停';
    audioPlayer.play().catch(e => {
        console.log("播放被阻止:", e);
        // 如果自动播放被阻止，显示播放按钮
        isPlaying = false;
        playBtn.textContent = '播放';
    });
}

// 暂停歌曲
function pauseSong() {
    isPlaying = false;
    playBtn.textContent = '播放';
    audioPlayer.pause();
}

// 上一曲
function prevSong() {
    currentSongIndex--;
    if (currentSongIndex < 0) {
        currentSongIndex = songs.length - 1;
    }
    loadSong(currentSongIndex);
}

// 下一曲
function nextSong() {
    currentSongIndex++;
    if (currentSongIndex >= songs.length) {
        currentSongIndex = 0;
    }
    loadSong(currentSongIndex);
}

// 更新进度条
function updateProgress() {
    if (isDraggingProgress) return;
    
    const { currentTime, duration } = audioPlayer;
    const progressPercent = (currentTime / duration) * 100;
    progress.value = progressPercent;
    
    currentTimeEl.textContent = formatTime(currentTime);
    if (duration) {
        durationEl.textContent = formatTime(duration);
    }
    
    updateLyrics();
}

// 设置进度
function setProgress() {
    const duration = audioPlayer.duration;
    audioPlayer.currentTime = (progress.value / 100) * duration;
}

// 设置音量
function setVolume() {
    audioPlayer.volume = volumeControl.value;
}

// 格式化时间
function formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
}

// 初始化播放列表
function initPlaylist() {
    playlistEl.innerHTML = '';
    songs.forEach((song, index) => {
        const li = document.createElement('li');
        li.textContent = `${song.title} - ${song.artist}`;
        li.addEventListener('click', () => {
            currentSongIndex = index;
            loadSong(currentSongIndex);
            playSong();
        });
        playlistEl.appendChild(li);
    });
}

// 搜索功能
function searchSongs() {
    const term = searchEl.value.toLowerCase();
    const items = playlistEl.querySelectorAll('li');
    
    items.forEach((item, index) => {
        const song = songs[index];
        const text = `${song.title} ${song.artist}`.toLowerCase();
        if (text.includes(term)) {
            item.style.display = 'block';
        } else {
            item.style.display = 'none';
        }
    });
}

// 事件监听
playBtn.addEventListener('click', () => {
    isPlaying ? pauseSong() : playSong();
});

prevBtn.addEventListener('click', prevSong);
nextBtn.addEventListener('click', nextSong);

audioPlayer.addEventListener('timeupdate', updateProgress);
audioPlayer.addEventListener('ended', nextSong);
audioPlayer.addEventListener('loadedmetadata', updateProgress);

progress.addEventListener('input', () => {
    isDraggingProgress = true;
    const duration = audioPlayer.duration || 0;
    currentTimeEl.textContent = formatTime((progress.value / 100) * duration);
});

progress.addEventListener('change', () => {
    isDraggingProgress = false;
    setProgress();
});

volumeControl.addEventListener('input', setVolume);

searchEl.addEventListener('input', searchSongs);

// 初始化
loadSong(currentSongIndex);
initPlaylist();